package com.example.orderservice.actor;

import akka.actor.AbstractActor;
import akka.actor.Props;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import com.example.orderservice.event.*;
import com.example.orderservice.service.OrderEventPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 订单Actor
 * 处理订单相关的业务逻辑，并发布事件到RocketMQ
 */
@Component("orderActor")
@Scope("prototype")
public class OrderActor extends AbstractActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
    
    @Autowired
    private OrderEventPublisher eventPublisher;

    public static Props props() {
        return Props.create(OrderActor.class);
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(CreateOrder.class, this::handleCreateOrder)
                .match(PayOrder.class, this::handlePayOrder)
                .match(CancelOrder.class, this::handleCancelOrder)
                .matchAny(o -> log.warning("收到未知消息: {}", o))
                .build();
    }

    /**
     * 处理创建订单命令
     */
    private void handleCreateOrder(CreateOrder createOrder) {
        log.info("处理创建订单请求: {}", createOrder.getOrderId());
        
        try {
            // 模拟订单创建业务逻辑
            Thread.sleep(100); // 模拟处理时间
            
            // 发布订单创建事件
            OrderCreatedEvent event = new OrderCreatedEvent(
                createOrder.getOrderId(),
                createOrder.getCustomerId(),
                createOrder.getItems(),
                createOrder.getTotalAmount()
            );
            
            eventPublisher.publishOrderEvent(event);
            
            log.info("订单创建成功，事件已发布: {}", createOrder.getOrderId());
            
            // 回复成功消息
            getSender().tell(new OrderCreated(createOrder.getOrderId(), "SUCCESS"), getSelf());
            
        } catch (Exception e) {
            log.error("创建订单失败: {}", e.getMessage());
            getSender().tell(new OrderCreated(createOrder.getOrderId(), "FAILED"), getSelf());
        }
    }

    /**
     * 处理支付订单命令
     */
    private void handlePayOrder(PayOrder payOrder) {
        log.info("处理支付订单请求: {}", payOrder.getOrderId());
        
        try {
            // 模拟支付处理逻辑
            Thread.sleep(150);
            
            // 发布订单支付事件
            OrderPaidEvent event = new OrderPaidEvent(
                payOrder.getOrderId(),
                payOrder.getPaymentId(),
                payOrder.getPaymentMethod(),
                payOrder.getAmount()
            );
            
            eventPublisher.publishOrderEvent(event);
            
            log.info("订单支付成功，事件已发布: {}", payOrder.getOrderId());
            
            getSender().tell(new OrderPaid(payOrder.getOrderId(), "SUCCESS"), getSelf());
            
        } catch (Exception e) {
            log.error("支付订单失败: {}", e.getMessage());
            getSender().tell(new OrderPaid(payOrder.getOrderId(), "FAILED"), getSelf());
        }
    }

    /**
     * 处理取消订单命令
     */
    private void handleCancelOrder(CancelOrder cancelOrder) {
        log.info("处理取消订单请求: {}", cancelOrder.getOrderId());
        
        try {
            // 模拟取消订单逻辑
            Thread.sleep(80);
            
            // 发布订单取消事件
            OrderCancelledEvent event = new OrderCancelledEvent(
                cancelOrder.getOrderId(),
                cancelOrder.getReason()
            );
            
            eventPublisher.publishOrderEvent(event);
            
            log.info("订单取消成功，事件已发布: {}", cancelOrder.getOrderId());
            
            getSender().tell(new OrderCancelled(cancelOrder.getOrderId(), "SUCCESS"), getSelf());
            
        } catch (Exception e) {
            log.error("取消订单失败: {}", e.getMessage());
            getSender().tell(new OrderCancelled(cancelOrder.getOrderId(), "FAILED"), getSelf());
        }
    }

    // 命令消息类
    public static class CreateOrder {
        private String orderId;
        private String customerId;
        private List<OrderItem> items;
        private Double totalAmount;

        public CreateOrder(String orderId, String customerId, List<OrderItem> items, Double totalAmount) {
            this.orderId = orderId;
            this.customerId = customerId;
            this.items = items;
            this.totalAmount = totalAmount;
        }

        // Getters
        public String getOrderId() { return orderId; }
        public String getCustomerId() { return customerId; }
        public List<OrderItem> getItems() { return items; }
        public Double getTotalAmount() { return totalAmount; }
    }

    public static class PayOrder {
        private String orderId;
        private String paymentId;
        private String paymentMethod;
        private Double amount;

        public PayOrder(String orderId, String paymentId, String paymentMethod, Double amount) {
            this.orderId = orderId;
            this.paymentId = paymentId;
            this.paymentMethod = paymentMethod;
            this.amount = amount;
        }

        // Getters
        public String getOrderId() { return orderId; }
        public String getPaymentId() { return paymentId; }
        public String getPaymentMethod() { return paymentMethod; }
        public Double getAmount() { return amount; }
    }

    public static class CancelOrder {
        private String orderId;
        private String reason;

        public CancelOrder(String orderId, String reason) {
            this.orderId = orderId;
            this.reason = reason;
        }

        // Getters
        public String getOrderId() { return orderId; }
        public String getReason() { return reason; }
    }

    // 响应消息类
    public static class OrderCreated {
        private String orderId;
        private String status;

        public OrderCreated(String orderId, String status) {
            this.orderId = orderId;
            this.status = status;
        }

        // Getters
        public String getOrderId() { return orderId; }
        public String getStatus() { return status; }
    }

    public static class OrderPaid {
        private String orderId;
        private String status;

        public OrderPaid(String orderId, String status) {
            this.orderId = orderId;
            this.status = status;
        }

        // Getters
        public String getOrderId() { return orderId; }
        public String getStatus() { return status; }
    }

    public static class OrderCancelled {
        private String orderId;
        private String status;

        public OrderCancelled(String orderId, String status) {
            this.orderId = orderId;
            this.status = status;
        }

        // Getters
        public String getOrderId() { return orderId; }
        public String getStatus() { return status; }
    }
}

